<template>
  <view>
    <u-navbar title="发起报修" :background="{ backgroundColor: '#9CE0FF' }" :border-bottom="false" title-color="#000" title-size="37" />
    <view id="container" class="flex flex-column oys" :style="{minHeight: `calc(100vh - ${top+2}px)`,maxHeight: `calc(100vh - ${top+2}px)`}">
      <view class="flex1">
        <view class="mt-20">
          <sub-title class="mt-20" title="基础信息"></sub-title>
          <view class="p-lr-40 mb-20">
            <view class="fz-30 lh-42 mt-30 flex justify-between border-bottom-CCCCCC pb-30">
              <text class="fz-32 color-FF6262 w-14">*</text>
              <text class="w-200 color-333333 font-bold pl-20">所属医院</text>
              <view class="flex1 text-right color-888888">
                <u-input :value="formHospitalLabel" type="select" placeholder="选择医院" height="30" input-align="right" @click="isShowHospitalSelect = true"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-30 flex justify-between border-bottom-CCCCCC pb-30">
              <text class="fz-32 color-FF6262 w-14">*</text>
              <text class="w-200 font-bold color-333333 pl-20">所属科室</text>
              <view class="flex1 text-right color-888888">
                <u-input :value="formDepartmentLabel" type="select" placeholder="选择科室" height="30" input-align="right" @click="isShowDepartmentSelect = true"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-30 flex justify-between border-bottom-CCCCCC pb-30">
              <text class="fz-32 color-FF6262 w-14">*</text>
              <text class="w-200 font-bold color-333333 pl-20">负责公司</text>
              <view class="flex1 text-right color-888888 break-all">
                <!-- <u-input v-if="!isCompanyRole" :value="formCompanyLabel" type="select" placeholder="选择公司" height="30" input-align="right" @click="isShowCompanySelect = true"/> -->
                <view>{{ companyName || '-' }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="mt-20">
          <sub-title class="mt-20" title="设备信息"></sub-title>
          <view class="p-lr-40 mb-20">
            <view class="lh-42 mt-20 flex">
              <view class="h-60 w-150 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-20" @tap="gotoDeviceSelect">
                <text>选择设备</text>
              </view>
              <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="resetDevice">
                <text>清除</text>
              </view>
            </view>
            <view class="fz-30 lh-42  mt-20 flex justify-between align-center">
              <text class="fz-32 color-FF6262 w-14">*</text>
              <text class="w-200 color-333333 font-bold">设备名称</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.deviceName" placeholder="点击输入设备名称" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="64"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-200 color-333333 font-bold pl-14">设备编号</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.deviceNo" placeholder="点击输入设备编号" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="16"/>
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 flex justify-between align-center">
              <text class="w-200 color-333333 font-bold pl-14">分组房间</text>
              <view class="flex1 text-right color-888888">
                <u-input v-model="form.roomName" placeholder="点击输入分组房间" height="30" input-align="right" :disabled="!!form.deviceId" :maxlength="64"/>
              </view>
            </view>
          </view>
        </view>
        <view class="mt-20">
          <sub-title class="mt-20" title="故障内容"></sub-title>
          <view class="p-lr-40 mb-20">
            <view class="fz-30 lh-42 mt-20">
              <text class="fz-32 color-FF6262 w-14">*</text><text class="w-200 color-333333 font-bold">故障描述</text>
              <view class="mt-10 border-CCCCCC w-full pt-12 pb-20 pl-10">
                <textarea class="min-h-200 color-888888 fz-30" v-model="form.description" auto-height placeholder="请输入故障描述" placeholder-style="color:#CCCCCC;font-size:30rpx" maxlength="500" :show-confirm-bar="false" />
              </view>
            </view>
            <view class="fz-30 lh-42 mt-20 ">
              <text class="w-200 color-333333 font-bold">拍照</text>
              <view class="flex flex-wrap mt-20">
                <!-- 图片缩略图 -->
                <view class="relative mr-30" v-for="(item, index) in photoFiles" :key="index">
                  <image class="h-150 w-150" :data-cur="item.url" :src="item.url" @tap="previewImage" />
                  <!--  移除图片的按钮  -->
                  <view class="absolute delBtn top-0 right-0" @tap.stop="removeImage(index)" >
                    <image class="h-50 w-50" src="@/static/images/workList/delPhoto.png"/>
                  </view>
                </view>
                <!-- 图片上传按钮 -->
                <view v-if="photoFiles.length < 5" class="h-150 w-150 bg-CCCCCC flex align-center justify-center" @tap="uploadImage()">
                  <image class="h-50 w-50" src="@/static/images/workList/camera.png"></image>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="min-h-174 sticky bottom0 bg-fff pt-30 border-top-EEEEEE">
        <view class="w-250 h-80 br-10 bg-19BE6B color-fff fz-30 text-center lh-80 margin-0-auto" @tap="confirm">
          <text>提交</text>
        </view>
      </view>
    </view>

    <u-select v-model="isShowHospitalSelect" :list="hospitalList" mode="single-column" value-name="hospitalId" label-name="name" @confirm="confirmHospitalId"/>
    <u-select v-model="isShowDepartmentSelect" :list="departmentList" mode="single-column" value-name="departmentId" label-name="name" @confirm="confirmDepartmentId"/>
    <!-- <u-select v-model="isShowCompanySelect" :list="companyList" mode="single-column" value-name="companyId" label-name="companyName" @confirm="confirmCompanyId"/> -->

    <!--图片加水印画板-->
    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="`mycanvas`" >
    </canvas>

    <!--图片上传中模态框-->
    <!-- #ifndef MP-WEIXIN -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" v-model="isUploading">
      <view class="h-200 flex flex-column align-center justify-center font-bold color-888888 lh-33 bg-fff">
        <text class="mb-10">图片上传中</text>
        <u-loading mode="circle"></u-loading>
      </view>
    </u-modal>
    <!-- #endif -->

    <!--微信小程序使用cover-view解决textarea层级过高问题-->

    <!-- #ifdef MP-WEIXIN -->
    <cover-view class="fixed top0 w-full min-100vh bg-00000060 flex align-center justify-center z-999"
      v-show="isUploading" @touchmove.stop.prevent="">
      <cover-view class="h-200 w-600 br-20 text-center lh-200 font-bold color-888888 lh-33 bg-fff">
        图片上传中
      </cover-view>
    </cover-view>
    <!-- #endif -->

    <!--图片加水印画板-->
    <canvas class="absolute top-99999"
            v-if="windowWidth !== 0 && windowHeight !== 0"
            :style="{'width':`${windowWidth}px`,'height': `${windowHeight}px`}"
            :canvas-id="`mycanvas`" >
    </canvas>
  </view>
</template>

<script>
import SubTitle from "@/components/SubTitle/SubTitle";
import {optionHospitalForCompany} from '@/api/hospital/hospital'
import {optionDepartment} from '@/api/hospital/department'
import {startWorkOrder} from '@/api/repair/workOrder'
import {companyOption} from '@/api/basic/company'
import uploadMaskImg from "@/mixins/uploadMaskImg";
import getNavBarHeight from "@/mixins/getNavBarHeight";

export default {
  name: "start-repair-work-order",
  mixins: [uploadMaskImg, getNavBarHeight],
  components: {SubTitle},
  data() {
    return {
      form: {
        hospitalId: "",
        departmentId: "",
        companyId: "",
        deviceId: "",
        deviceNo: "",
        deviceName: "",
        description: "",
        ossIdList: [],
        initiator: "",
        roomName: ""
      },
      isUploading: false,
      photoFiles: [],
      isShowHospitalSelect: false,
      hospitalList: [],
      isShowDepartmentSelect: false,
      departmentList: [],
      companyName: '',
      isShowCompanySelect: false,
      isAdminRole:false
    }
  },
  computed: {
    formHospitalLabel() {
      return this.hospitalList.find(item => item.hospitalId === this.form.hospitalId)?.name || ''
    },
    formDepartmentLabel() {
      return this.departmentList.find(item => item.departmentId === this.form.departmentId)?.name || ''
    }
  },
  onLoad(option) {
    // this.isAdminRole = this.$auth.hasRole(['admin'])
    this.isCompanyRole = this.$auth.hasRoleOr(['manager', 'admin','co-admin','engineer'])
    this.reset()
    // if (option.hospitalId) {
    //   this.form.hospitalId = option.hospitalId
    // }
    // if (option.departmentId) {
    //   this.form.departmentId = option.departmentId
    // }
    // if (option.companyId) {
    //   this.form.companyId = option.companyId
    // }
    // if (option.deviceId) {
    //   this.form.deviceId = option.deviceId
    //   device(this.form.deviceId).then(res => {
    //     this.form.deviceName = res.data.deviceName || ''
    //     this.form.deviceNo = res.data.deviceNo || ''
    //     this.form.roomName = res.data.roomName || ''
    //   })
    // }
    Promise.all([
      this.getCompanyDetail(),
      this.getHospitalList(),
      this.getDepartmentList()
    ])
  },
  methods: {
    reset() {
      this.form = {
        hospitalId: this.$store.getters.curHospitalId !== -1 ? this.$store.getters.curHospitalId : "",
        departmentId: "",
        companyId: this.$store.getters.companyId !== -1 ? this.$store.getters.companyId : "",
        deviceId: "",
        deviceNo: "",
        deviceName: "",
        description: "",
        ossIdList: [],
        initiator: this.$store.getters.name || "",
        roomName: ""
      }
      this.photoFiles = []
    },
    resetDevice() {
      this.form.deviceId = ''
      this.form.deviceName = ''
      this.form.deviceNo = ''
      this.form.roomName = ''
    },
    /** 查询医院列表 */
    getHospitalList() {
      return optionHospitalForCompany(this.form.companyId).then(res => {
        this.hospitalList = res.data
        return Promise.resolve(res)
      })
    },
    /** 查询科室列表(依赖所属医院) */
    getDepartmentList() {
      this.departmentList = []
      if (!this.form.hospitalId) {
        return Promise.resolve('医院id为空')
      }
      return optionDepartment({hospitalId: this.form.hospitalId,companyId:this.form.companyId}).then(res => {
        this.departmentList = res.data
        return Promise.resolve(res)
      })
    },
     /** 查询公司详细(公司的人默认带入公司ID) */
    getCompanyDetail() {
     companyOption({companyId: this.form.companyId}).then(res => {
       const companyName = res.data.find(item => item.companyId === this.form.companyId)?.companyName
        this.companyName = companyName || ''
     })
    },
    confirmHospitalId([{value: hospitalId}]) {
      if (hospitalId) {
        this.form.hospitalId = hospitalId
      }
      this.onHospitalChange()
    },
    /** 所属医院改变, 清空所属科室, 并重新获取新的所属科室列表 */
    onHospitalChange() {
      if (this.form.departmentId) {
        this.form.departmentId = ''
      }
      this.getDepartmentList()
    },
    confirmDepartmentId([{value: departmentId}]) {
      if (!departmentId || departmentId !== this.form.departmentId) {
        this.resetDevice()
      }
      if (departmentId) {
        this.form.departmentId = departmentId
      }
    },
    gotoDeviceSelect() {
      if (!this.form.hospitalId || !this.form.departmentId) {
        this.$u.toast('请先选择医院和科室')
        return
      }
      uni.navigateTo({
        url: `/pages/repair/choose-device?hospitalId=${this.form.hospitalId}&departmentId=${this.form.departmentId}&deviceId=${this.form.deviceId || ''}`,
        events: {
          confirm: (data) => {
            this.form.deviceId = data.deviceId
            this.form.deviceNo = data.deviceNo
            this.form.deviceName = data.deviceName
            this.form.roomName = data.roomName
          }
        },
      })
    },
    // 点击预览
    previewImage (e) {
      const current = e.currentTarget.dataset.cur;
      const urls = this.photoFiles.map(el => el.url);
      uni.previewImage({
        current: current,
        urls: urls, //需要预览的图片链接列表
        indicator: "none", //图片指示器样式 "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器
      });
    },
    // 删除图片
    removeImage (index) {
      this.photoFiles.splice(index, 1)
    },
    // 上传图片
    uploadImage() {
      this.uploadMaskImg({sourceType: ['album', 'camera']})
    },
    // 上传图片成功回调(uploadMaskImg的方法重写)
    uploadSuccessCallback({data}) {
      this.photoFiles.push({
        url: data.url,
        ossId: data.ossId,
      })
    },
    // 水印内容(uploadMaskImg的方法重写)
    maskContent (ctx, image) {
      // ctx.strokeText(this.form.deviceName || '-', image.width * 0.092, image.width * 0.23);
      // ctx.fillText(this.form.deviceName || '-', image.width * 0.092, image.width * 0.23)
      //
      // ctx.strokeText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28);
      // ctx.fillText(this.$store.getters.staffName || '-', image.width * 0.092, image.width * 0.28)
      //
      // ctx.strokeText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33);
      // ctx.fillText(dayjs().format('YYYY-MM-DD HH:mm:ss'), image.width * 0.092, image.width * 0.33)
    },
    validate() {
      if (!this.form.hospitalId) {
        this.$u.toast('所属医院不能为空')
        return false
      }
      if (!this.form.departmentId) {
        this.$u.toast('所属科室不能为空')
        return false
      }
      if (!this.form.companyId) {
        this.$u.toast('负责公司不能为空')
        return false
      }
      if (!this.form.deviceName) {
        this.$u.toast('设备名称不能为空')
        return false
      }
      if (!this.form.description) {
        this.$u.toast('故障描述不能为空')
        return false
      }
      return true
    },
    confirm() {
      if (this.loading) {return}
      if (!this.validate()) {return}
      this.form.ossIdList = this.photoFiles.map(el => el.ossId).filter(el => el)
      this.loading = true
      uni.showLoading({title: '提交中'})
      startWorkOrder(this.form).then(() => {
        uni.hideLoading()
        uni.navigateBack({delta: 1})
      }).catch(() => {
        setTimeout(()=>{
          uni.hideLoading()
        },1500)
      })
      .finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style>
page{
  background-color: #FFFFFF;
}
</style>
